package org.xwalk.core;


import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;



public class XWalkJavascriptResultHandler   implements XWalkJavascriptResult  {

    private ArrayList<Object> constructorTypes;
    private ArrayList<Object> constructorParams;
    private ReflectMethod postWrapperMethod;


    private XWalkCoreWrapper coreWrapper;
    private Object bridge;

    protected Object getBridge() {
        return bridge;
    }

    public XWalkJavascriptResultHandler(Object bridge) {
        this.bridge = bridge;
        reflectionInit();
    }


    public void confirm() {
        try {
            confirmMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        
    }

    private ReflectMethod confirmMethod = new ReflectMethod(null, "confirm");


    public void confirmWithResult(final String promptResult) {
        try {
            confirmWithResultStringMethod.invoke(promptResult);
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        
    }

    private ReflectMethod confirmWithResultStringMethod = new ReflectMethod(null, "confirmWithResult");


    public void cancel() {
        try {
            cancelMethod.invoke();
        } catch (UnsupportedOperationException e) {
            if (coreWrapper == null) {
                throw new RuntimeException("Crosswalk's APIs are not ready yet");
            } else {
                XWalkCoreWrapper.handleRuntimeError(e);
            }
        }
        
    }

    private ReflectMethod cancelMethod = new ReflectMethod(null, "cancel");


    void reflectionInit() {
        XWalkCoreWrapper.initEmbeddedMode();

        coreWrapper = XWalkCoreWrapper.getInstance();
        if (coreWrapper == null) {
            XWalkCoreWrapper.reserveReflectObject(this);
            return;
        }

        confirmMethod.init(bridge, null,
                "confirmSuper");
        confirmWithResultStringMethod.init(bridge, null,
                "confirmWithResultSuper", String.class);
        cancelMethod.init(bridge, null,
                "cancelSuper");
    }

}
